package com.example.demo.Service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;

import com.auth0.jwt.algorithms.Algorithm;

import com.example.demo.Repository.IEmployeeRepository;
import com.example.demo.Repository.IHRRepository;

/**
 * @version: V0.3
 * @author: 郑皓杰 吴嘉鑫
 * @className: TokenService
 * @packageName: com.example.demo.Service
 * @description: 此类封装了token相关操作
 * @data: 2021-07-14
 **/

@Service
public class TokenService {
	@Autowired
	private IHRRepository hrRepository;
	@Autowired
	private IEmployeeRepository empRepository;
	
	

	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: getToken
	* @description: 根据username和password生成一个token
	* @param:  String username,String password
	* @return: String
	* @throws: 
	*/
	public String getToken(String username,String password) {
		Date start = new Date();
        long currentTime = System.currentTimeMillis() + 1000*1800;//半小时有效时间
        Date end = new Date(currentTime);
        String token = "";

        token = JWT.create().withClaim("username", username).withClaim("password", password).withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(password));//创造
        return token;
        
	}	
	
	
	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: getCompanyIDfromToken
	* @description: 根据获取的token查询companyid
	* @param:  String token
	* @return: Integer
	* @throws: 
	*/
	public Integer getCompanyIDfromToken(String token) {
		String username = JWT.decode(token).getClaim("username").asString();
		Integer CompanyID = hrRepository.findCompanyIDbyUsername(username);
		return CompanyID;
	}
	
	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: getEmpidfromToken
	* @description: 根据获取的token查询empid
	* @param:  String token
	* @return: Integer
	* @throws: 
	*/
	public Integer getEmpidfromToken(String token) {
		String username = JWT.decode(token).getClaim("username").asString();
		Integer empid = empRepository.findempidByUsername(username);
		return empid;	
	}
	
	
	/**
	* @author:吴嘉鑫 郑皓杰
	* @methodsName: getCompanyNamefromToken
	* @description: 根据获取的token查询CompanyName
	* @param:  String token
	* @return: String
	* @throws: 
	*/
	public String getCompanyNamefromToken(String token) {
		String username = JWT.decode(token).getClaim("username").asString();
		String CompanyName = hrRepository.findCompanyNamebyUsername(username);
		return CompanyName;
	}
	
	
	/**
	* @author:郑皓杰
	* @methodsName: getUserNamefromToken
	* @description: 根据获取的token得出对应username
	* @param:  String token
	* @return: String
	* @throws: 
	*/
	public String getUserNamefromToken(String token) {
		return JWT.decode(token).getClaim("username").asString();
	}

}
